package lrscp.lib;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * put my most useful apis in it
 * 
 * @author lrscp
 */
public class Common {
	/**
	 * dumpStack
	 */
	public static void dumpStack() {
		Throwable stack = new Throwable();
		stack.printStackTrace();
	}

	/**
	 * excute /system/bin cmds
	 * 
	 * @return result of cmd
	 */
	public static String execCmd(String cmd) {
		try {
			Log.i("exec cmd = " + cmd);
			Process proc = Runtime.getRuntime().exec(cmd, null, null);
			InputStreamReader in = new InputStreamReader(proc.getInputStream());
			BufferedReader reader = new BufferedReader(in);
			StringBuffer buf = new StringBuffer();
			String line = null;
			while ((line = reader.readLine()) != null) {
				//Log.i("execCmd", line);
				buf.append(line + "\n");
			}
			return buf.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * excute /system/bin cmds
	 * 
	 * @return result of cmd
	 */
	public static String execCmd(String cmd, String[] containStrings) {
		try {
			Process proc = Runtime.getRuntime().exec(cmd, null, null);
			// install.waitFor();
			InputStreamReader in = new InputStreamReader(proc.getInputStream());
			BufferedReader reader = new BufferedReader(in);
			StringBuffer buf = new StringBuffer();
			String line = null;
			while ((line = reader.readLine()) != null) {
				//Log.i("execCmd", line);
				for(int i = 0; i < containStrings.length; i++){
					if(line.contains(containStrings[i])){
						buf.append(line + "\n");
						break;
					}
				}				
			}
			return buf.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * Find the pattern that matches and return the first group in regx "(***)".
	 * Such as: this("hello:1234", "hello:(\\d+)") and the result will be "1234".
	 * @param line
	 * @param regx
	 * @return
	 */
	static String findRegxGroup1(String line, String regx){
		Pattern pattern;
		Matcher matcher;
		
		pattern = Pattern.compile(regx);
		matcher = pattern.matcher(line);
		if(matcher.find()){
			return matcher.group(1);
		}
		
		return null;
	}

	/**
	 * open a file path. if file exists, return fd immediately. if path not
	 * exists, create the directories first, and then create the file
	 */
	public static File openFile(String path) {
		File fd = new File(path);
		if (fd.exists()) {
			return fd;
		}

		if (fd.isDirectory()) {
			fd.mkdirs();
		} else {
			File tmpFd = new File(fd.getParent());
			if (!tmpFd.exists()) {
				tmpFd.mkdirs();
			}
			try {
				fd.createNewFile();
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			}
		}
		return fd;
	}
	
	public static void retry(Runnable main, Runnable handleException, int retryCnt) {
        int retry = 0;
        while (retry < retryCnt) {
            try {
                main.run();
                return;
            } catch (Exception e) {
                handleException.run();
                retry++;
            }
        }
    }
	
	/**
	 * sleep without try and catch
	 * 
	 * @param time
	 */
	public static void sleep(long time) {
		try {
			Thread.sleep(time);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	/**
     * Remove the unexpected chars like '\' ':' in file name or path
     */
    public static String validateFileName(String fileName, char replaceChar) {
        char[] buf = new char[fileName.length()];
        fileName.getChars(0, fileName.length(), buf, 0);
        for (int i = 0; i < buf.length; i++) {
            if ("\t\r\n\\/:\"?*<>|".indexOf(buf[i]) != -1) {
                buf[i] = replaceChar;
            }
        }
        fileName = new String(buf);
        return fileName;
    }
	
    /** An easy way to write String to file, should declare permisson */
	public static void writeStringToFile(String path, String content, boolean append) {
        File fd = openFile(path);
        if (fd == null) {
            Log.e("can't open file = " + path);
            return;
        }
        if (fd.isDirectory()){
        	Log.e("cant't write String to directory!!");
        	return;
        }
        
        FileWriter fw;
        try {
            /** append String to File */
            fw = new FileWriter(fd, append);
            fw.append(content);
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    String getLine(String src, int num){
    	String[] lines = src.split("\n");
    	
    	String line = null;
    	if(num < 0){
    		line = lines[lines.length + num];
    	} else {
    		line = lines[num];
    	}
    	
    	return line;
    }
}
